package cn.edu.nsmc.modules.sys.service.impl;

import cn.edu.nsmc.common.utils.R;
import cn.edu.nsmc.common.utils.ShiroUtils;
import cn.edu.nsmc.config.Constant;
import cn.edu.nsmc.modules.sys.dao.SysRepairmanDao;
import cn.edu.nsmc.modules.sys.entity.SysUserEntity;
import cn.edu.nsmc.modules.sys.entity.excel.SysUserEntityExcel;
import cn.edu.nsmc.modules.sys.entity.vo.SysUserVO;
import cn.edu.nsmc.modules.sys.entity.vo.SysWorksheetRecordVo;
import cn.edu.nsmc.modules.sys.service.SysRepairmanService;
import cn.edu.nsmc.utils.FileUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SysRepairmanServiceImpl implements SysRepairmanService {
    @Autowired
    private SysRepairmanDao sysRepairmanDao;
    @Autowired
    private FileUtils fileUtils;

    @Override
    public R getList(SysUserEntity sysUserEntity,Integer page,Integer size) {
        List<SysUserVO> list = sysRepairmanDao.getList(page, size, sysUserEntity);
        Integer total = sysRepairmanDao.getNumber(sysUserEntity);
        Map<String,Object> data = new HashMap<>();
        data.put("list",list);
        data.put("total",total);
        return R.success("查询成功",data);
    }

    @Override
    public void getExcelTemplate(HttpServletResponse response) {
        try {
            fileUtils.getExcelFile("repExcel.xlsx",response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public R importRepairman(MultipartFile file,Long userId) {
        if (userId==null){
            return R.error("获取用户ID失败");
        }
        InputStream in = null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            R.error("读取文件失败");
        }
        Date creationTime=new Date(System.currentTimeMillis());
        EasyExcel.read(in, SysUserEntityExcel.class, new ReadListener<SysUserEntityExcel>() {
            /**
             * 单次缓存的数据量
             */
            public static final int BATCH_COUNT = 30;
            /**
             *临时存储
             */
            private List<SysUserEntityExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(SysUserEntityExcel data, AnalysisContext context) {
                data.setSalt(RandomStringUtils.randomAlphanumeric(20));
                data.setPassword(new Sha256Hash(Constant.DEFAULT_PASSWORD, data.getSalt()).toHex());
                //data.setStatus(1);
                //data.setType(5);
                if ("男".equals(data.getGenderString())){
                    data.setGender(1);
                }else {
                    data.setGender(0);
                }
                //默认的角色Id
                //获取创建者Id并设置
                data.setCreateTime(creationTime);
                //data.setMiniUse(0);
                //data.setMiniAttention(0);
                //询问小程序的逻辑
                cachedDataList.add(data);
                if (cachedDataList.size() >= BATCH_COUNT) {
                    saveData();
                    // 存储完成清理 list
                    cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                saveData();
            }

            /**
             * 加上存储数据库
             */
            private void saveData() {
                log.info("{}条数据，开始存储数据库！", cachedDataList.size());
                //to save
//                System.out.println(cachedDataList);
                sysRepairmanDao.importRepairman(userId,cachedDataList);
                log.info("存储数据库成功！");
            }
        }).sheet().doRead();
        return R.ok("导入维修人员信息成功");
    }

    @Override
    public void exportRepairman(SysUserEntity sysUserEntity, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        List<SysUserEntityExcel> data = sysRepairmanDao.exportRepairman(sysUserEntity);
        for (SysUserEntityExcel datum : data) {
            if (datum.getGender() == 1) {
                datum.setGenderString("男");
            } else {
                datum.setGenderString("女");
            }
            if ("0".equals(datum.getStatus())){
                datum.setStatus("禁用");
            }else {
                datum.setStatus("正常");
            }
            datum.setType(Constant.INT_TO_TYPE.get(datum.getTypeInt()));
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("维修人员信息统计表", "UTF-8").replaceAll("\\+", "%20");
        //response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SysUserEntityExcel.class).sheet("数据").doWrite(data);
    }

    @Override
    public R queryStatistics(SysUserEntity sysUserEntity) {
        return null;
    }

    @Override
    public void exportStatistics(SysUserEntity sysUserEntity, HttpServletResponse response) {

    }

    @Override
    public R getSelectList(String name) {
        List<Map<String,Object>> data=sysRepairmanDao.getSelectList(name);
        System.out.println(ShiroUtils.getUserId());
        return R.success("查询成功",data);
    }
}
